package com.atguigu.cart.interceptor;

import com.atguigu.cart.viewTo.UserInfoTo;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.viewVo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;

/*拦截器*/
//@Component
public class CartInterceptor implements HandlerInterceptor {


    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    /***
     * 拦截所有请求给ThreadLocal封装UserInfoTo对象
     * 1、从session中获取MemberResponseVo != null，登录状态，为UserInfoTo设置Id
     * 2、从request中获取cookie，找到user-key的value，
     * 目标方法执行之前：在ThreadLocal中存入用户信息【同一个线程共享数据】
     * 从session中获取数据【使用session需要cookie中的GULISESSION 值】
     */
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) {

         UserInfoTo userInfoTo = new UserInfoTo();
         HttpSession session = request.getSession();
         //获得当前登录用户的信息
         MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
         if(memberResponseVo != null) {
             userInfoTo.setUserId(memberResponseVo.getId());
         }

         Cookie[] cookies = request.getCookies();
         if(cookies != null) {
             Arrays.stream(cookies).filter(n->n.equals(CartConstant.TEMP_USER_COOKIE_NAME)).forEach(n->{
                 userInfoTo.setUserKey(n.getValue());
                 userInfoTo.setTempUser(true);
             });
         }

         userInfoTo.setUserKey(StringUtils.isEmpty(userInfoTo.getUserKey()) ?
                               UUID.randomUUID().toString() : userInfoTo.getUserKey());

         threadLocal.set(userInfoTo);
         return true;
     }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        // 获取当前用户的值
        // 1、判断是否登录；2、判断是否创建user-token的cookie
        if(Optional.ofNullable(userInfoTo).map(UserInfoTo::isTempUser).orElse(false)) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
